/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: shared_memory.cpp
 *
 * Purpose: shared memory implementation.
 *
 * Developer:
 *   wen.gu , 2019-10-06
 *
 * TODO:
 *
 ***************************************************************************/

 /******************************************************************************
 **    INCLUDES
 ******************************************************************************/


#if defined(HAVE_POSIX_SHM_API) && HAVE_POSIX_SHM_API
#include "panda/core/internal/shared_memory_impl.h"
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>


namespace panda
{
namespace core
{
namespace internal_impl
{
/******************************************************************************
 **    MACROS
 ******************************************************************************/



/******************************************************************************
 **    VARIABLE DEFINITIONS
 ******************************************************************************/

struct SharedMemObj
{    
    uint8_t* mData = nullptr;
    uint32_t mSize = 0;  
    std::string mFileName = "";
};

/******************************************************************************
 **    FUNCTION DEFINITIONS
 ******************************************************************************/


SharedMemObj* SharedMemoryAlloc(const std::string& name, uint32_t size)
{
    SharedMemObj* retShm = nullptr;
    uint8_t* pBuf = nullptr;
    int fd = shm_open(name.c_str(), O_CREAT | O_RDWR, 0666);

    if (fd >= 0)
    {
        int ret = ftruncate(fd, size);

        if (ret == 0)
        {
            void* ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

            if (ptr)
            {
                close(fd);
                retShm = new SharedMemObj;
                retShm->mData = (uint8_t*)ptr;
                retShm->mSize = size;
                retShm->mFileName = name; //todo?
            }
            else
            {
                close(fd);
                shm_unlink(name.c_str());
            }
        }
        else
        {
            close(fd);
            shm_unlink(name.c_str());
        }
    }

    return retShm;
}

SharedMemObj* SharedMemoryAttach(const std::string& name)
{
    SharedMemObj* retShm = nullptr;
    uint8_t* pBuf = nullptr;
    int fd = shm_open(name.c_str(), O_RDWR, 0666);

    if (fd >= 0)
    {
        stat statBuf;
        int ret = fstat(fd, &statbuf);

        if (ret)
        {
            void* ptr = mmap(0, statBuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

            if (ptr)
            {
                close(fd);
                retShm = new SharedMemObj;
                retShm->mData = (uint8_t*)ptr;
                retShm->mSize = statBuf.st_size;
                retShm->mFileName = ""; //todo?
            }
            else
            {
                close(fd);
            }
        }
        else
        {
            close(fd);
        }
    }

    return retShm;
}


void SharedMemoryFree(SharedMemObj* smo)
{
    if (smo)
    {
        if (smo->mData)
        {
            munmap(smo->mData, smo->mSize);
            smo->mData = nullptr;
        }
        
        if (!smo->mFileName.empty())
        {
            shm_unlink(smo->mFileName.c_str());
            smo->mFileName = "";
        }

        delete smo;
    }
}

uint8_t* SharedMemoryData(SharedMemObj* smo)
{
    return smo ? smo->mData : nullptr;
}

uint32_t SharedMemorySize(SharedMemObj* smo)
{
    return smo ? smo->mSize : 0;
}


} /** namespace internal_impl */
} /** namespace core */
} /** namespace panda */

#endif /** defined HAVE_POSIX_SHM_API */